package com.goudan.practice.tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 便利蜂解析字符串反序列化二叉树问题
 * 解析字符串："A(B(C(,),),E(,))" ,前序生成二叉树
 */
public class SerializeTreeByBLF {

    public static class Node {
        public String value;
        public Node left;
        public Node right;

        public Node(String data) {
            this.value = data;
        }
    }

    public static void main(String[] args) {
        String str = "A(B(C(,),),E(,))";
        Queue<String> ans = strToQueue(str);
        Queue<String> ans2 = strToQueue2(str);
        System.out.println(ans);
        Node head = preb(ans);
        System.out.println(head);
    }

    private static Queue<String> strToQueue2(String str) {



        return null;
    }

    /**
     * 傻白甜写法
     */
    private static Queue<String> strToQueue(String str) {
        char[] charArray = str.toCharArray();
        Queue<String> ans = new LinkedList<>();
        for (int i = 0; i < charArray.length; i++) {
            if (i > 1 && ",".equals(String.valueOf(charArray[i])) && "(".equals(String.valueOf(charArray[i - 1]))) {
                ans.add(null);
            } else if (i > 1 && ")".equals(String.valueOf(charArray[i])) && ",".equals(String.valueOf(charArray[i - 1]))) {
                ans.add(null);
            } else if ("(".equals(String.valueOf(charArray[i]))) {
                continue;

            } else if (i > 1 && ",".equals(String.valueOf(charArray[i])) && ")".equals(String.valueOf(charArray[i - 1]))) {
                continue;
            } else if (i > 1 && ")".equals(String.valueOf(charArray[i])) && ")".equals(String.valueOf(charArray[i - 1]))) {
                continue;
            } else {
                ans.add(String.valueOf(charArray[i]));
            }

        }
        return ans;
    }

    public static Node preb(Queue<String> prelist) {
        String value = prelist.poll();
        if (value == null) {
            return null;
        }
        Node head = new Node(value);
        head.left = preb(prelist);
        head.right = preb(prelist);
        return head;
    }

    /**
     * 二叉树序列化
     */
    public static void pres(Node head, Queue<String> ans) {
        if (head == null) {
            ans.add(null);
        } else {
            ans.add(String.valueOf(head.value));
            pres(head.left, ans);
            pres(head.right, ans);
        }
    }
}
